package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomFlag;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.CustomFeature;
import br.com.telescope.t2.feature.MethodFeature;
import br.com.telescope.t2.menu.Menu;
import br.com.telescope.t2.menu.MenuItem;
import br.com.telescope.t2.menu.XmlMenu;
import java.util.HashMap;
import solutions.ferpa.ztest.ent.*;

/**
 * Importação dos menus.
 * <p>
 * Interface para importar os menus com os dados informados pelo ambiente 
 * de desenvolvimento app-info.xml.
 * <P>
 * Telescope origin: RTMENU.IMP_MENUS
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class ImpMenus extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTMENU.IMP_MENUS";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Importação dos menus");
    }
    
    
    // Record items
    private DomFlag aExcluirMenusAtuais;
    
    // Query items
    
    @Override
    public void initAttributes() {
        
        aExcluirMenusAtuais = new DomFlag();
        aExcluirMenusAtuais.context(ctx).name("EXCLUIR_MENUS_ATUAIS").label("Excluir menus atuais").unbound(true);
        
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="IMPORT">
    public class FImport extends CustomFeature {
        
        @Override
        public void initForm() {
            addField(aExcluirMenusAtuais, "opt");
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("IMPORTAR_MENUS")).label("Importar menus").icon("importar.gif");
        }
        
        {
            setFeatureName("IMPORT");
            setTitle("Tela para importação de menus");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="IMPORTAR_MENUS">
    public class FImportarMenus extends MethodFeature {
        
        @Override
        public void run() {
            preRun();
            try {
                importarMenus();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("IMPORTAR_MENUS");
            setTitle("Importar menus");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FImport());
        addFeature(new FImportarMenus());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "IMPORT";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public String getExcluirMenusAtuais() {
        return aExcluirMenusAtuais.getValue();
    }
    
    public void setExcluirMenusAtuais(String value) {
        this.aExcluirMenusAtuais.setValue(value);
    }
    // </editor-fold>
    
    /**
     * Importar menus.
     */
    private void importarMenus() throws AdsException {
        // <user-code id="771996" parentId="769114" hashcode="62cae49d" length="4478">
        //import br.com.telescope.t2.menu.Menu;
        //import br.com.telescope.t2.menu.MenuItem;
        //import br.com.telescope.t2.menu.XmlMenu;
        //import java.util.HashMap;
        
        try {
            ctx.beginTransaction();
        
            EntMenus menu = new EntMenus(ctx);
            EntItensMenus itemMenu = new EntItensMenus(ctx);
            HashMap<String, Menu> menusMap = new HashMap<String, Menu>();
        
            if (ctx.getParameter("A_EXCLUIR_MENUS_ATUAIS").equals("S")) {
                itemMenu.del("select id from itens_menus");
                menu.del("select id from menus");
            }
        
            StringBuilder out = new StringBuilder(500);
            XmlMenu xml = new XmlMenu();
        
            for (Menu m : xml.getMenus()) {
                menu.nullify();
                try {
                    menu.findByMenu(m.getName().trim().toUpperCase());
                } catch (RecordNotFoundException ex) {
                    menu.setMenu(m.getName().trim().toUpperCase());
                    if (m.getLabel() == null || m.getLabel().length() == 0) {
                        menu.setTitulo(m.getName());
                    } else {
                        menu.setTitulo(m.getLabel());
                    }
                    menu.setSequencia(m.getSequence());
                    menu.setTopo(m.isTop() ? "S" : "N");
                    menu.ins();
                }
        
                m.setId(menu.valueOfId());
        
                menusMap.put(m.getName(), m);
            }
        
            out.append("<ol>");
            for (Menu m : xml.getMenus()) {
                out.append("<li>").append(m.getLabel()).append("(").append(m.getName()).append(")");
        
                if (m.getItems().size() > 0) {
                    out.append("<ol>");
                }
                for (MenuItem item : m.getItems()) {
                    itemMenu.nullify();
                    EntInterfacesSistemas intf = new EntInterfacesSistemas(ctx);
                    if (item.getService() != null) {
                        try {
                            intf.findByNome(item.getService());
                            itemMenu.setInterfaceId(intf.valueOfId());
                        } catch (RecordNotFoundException e) {
                            itemMenu.setUrl(item.getService());
                        }
                    } else {
                        itemMenu.setUrl(item.getUrl());
                    }
        
                    if (item.getSubMenu() != null) {
                        if (menusMap.get(item.getSubMenu()) != null) {
                            itemMenu.setSubMenuId(menusMap.get(item.getSubMenu()).getId());
                        }
                    }
                    try {
                        itemMenu.findByMenuIdTitulo(menusMap.get(m.getName()).getId(), item.getLabel().trim());
                        if (intf.isNotNull()) {
                            itemMenu.setInterfaceId(intf.valueOfId());
                        }
                        if (itemMenu.getInterfaceId().isNull() && itemMenu.getSubMenuId().isNull() && itemMenu.getUrl().isNull()) {
                            ctx.p("Menu" + itemMenu.getTitulo() + " não pode ser inserido, por não localizar interface ou sub-menu");
                            continue;
                        } else {
                            itemMenu.upd();
                        }
                    } catch (RecordNotFoundException ex) {
                        itemMenu.setMenuId(menusMap.get(m.getName()).getId());
                        itemMenu.setSequencia(item.getSequence());
                        if (item.getLabel() == null || item.getLabel().isEmpty()) {
                            itemMenu.setTitulo("?????");
                        } else {
                            itemMenu.setTitulo(item.getLabel().trim());
                        }
                        itemMenu.setPublico("S");
                        itemMenu.setAtivo("S");
                        if (itemMenu.getInterfaceId().isNull() && itemMenu.getSubMenuId().isNull() && itemMenu.getUrl().isNull()) {
                            ctx.p("Menu" + itemMenu.getTitulo() + " não pode ser inserido, por não localizar interface ou sub-menu");
        
                            continue;
                        } else {
                            itemMenu.ins();
                        }
                    }
        
                    out.append("<li>").append(item.getLabel()).append("(").append(item.getService() != null ? item.getService() : "").append(")</li>");
                }
                if (m.getItems().size() > 0) {
                    out.append("</ol>");
                }
        
                out.append("</li>");
            }
            out.append("</ol>");
        
            ctx.p(out.toString());
            ctx.endTransaction();
            refreshSessionMenu();
        } catch (AdsException ex) {
            ctx.abortTransactionUnchecked();
            throw ex;
        } catch (Exception ex) {
            ctx.abortTransactionUnchecked();
            throw new AdsException(ex,
                    "",
                    AdsException.UNKNOWN,
                    ex.toString());
        }
        // </user-code>
    }
}
